import React, { Suspense, useState } from 'react'
import { Button, Card, Divider, message, Modal, Spin, Switch } from 'antd'
import { MarkdownEditor, MarkdownRender, Panel } from '@/base/components'
import {
  CloseOutlined,
  EyeOutlined,
  UnorderedListOutlined,
} from '@ant-design/icons'
import { Upload } from '@icon-park/react'
import { useApp } from '@/base/hooks'
import { CategoryList } from '@/domain/category'
import { NoteQueryParams, useNotes } from '@/domain/note'

interface NoteWritePageProps {
  isUpgrading?: boolean //是否是修改笔记
  onCancelUpgrading?: () => void
  currentNoteId?: number
  currentNoteValue?: string
  currentCategoryId?: number
  currentCategoryName?: string
  currentIsPublic?: number
}
const NoteWritePage: React.FC<NoteWritePageProps> = ({
  isUpgrading = false,
  onCancelUpgrading,
  currentNoteId = null,
  currentNoteValue = null,
  currentCategoryId = null,
  currentCategoryName = null,
  currentIsPublic = 1,
}) => {
  /**
   * 用户信息
   * app 信息
   */
  const app = useApp()
  /**
   * 获取和问题相关的笔记列表
   */

  const [noteQueryParams] = useState<NoteQueryParams>({
    page: 1,
    pageSize: 10,
  })
  const { createNoteHandle, updateNoteHandle } = useNotes(noteQueryParams)

  /**
   * 预览
   */
  const [isShowPreview, setIsShowPreview] = useState(false)
  /**
   * 分类选择
   */
  const [isShowCategory, setIsShowCategory] = useState(false)
  const [selectedCategoryName, setSelectedCategoryName] =
    useState(currentCategoryName)
  const [selectedCategoryId, setSelectedCategoryId] =
    useState(currentCategoryId)
  const handleCategorySelect = (id: number, name: string) => {
    setSelectedCategoryName(name)
    setSelectedCategoryId(id)
    setIsShowCategory(false)
  }
  /**
   * 是否公开
   */
  const [isPublic, setIsPublic] = useState<number>(currentIsPublic)

  /**
   * 笔记内容
   */
  const [value, setValue] = useState(currentNoteValue)
  const setValueHandle = (value: string) => {
    setValue(value)
  }
  /**
   * 取消修改
   */
  const handleCancel = () => {
    if (onCancelUpgrading) {
      onCancelUpgrading()
    }
  } /**
   * 提交笔记处理事件
   */
  const createNoteClickHandle = async () => {
    if (!app.isLogin) {
      message.info('请先登录')
      return
    }
    try {
      if (!isUpgrading) {
        const noteId = await createNoteHandle(
          selectedCategoryId as number,
          value as string,
          isPublic,
        )
        // 校验一下 noteId
        if (noteId == null) {
          throw new Error('提交失败')
        }
        message.success('笔记已提交')
      } else {
        // 修改笔记操作
        await updateNoteHandle(currentNoteId as number, {
          isPublic: isPublic,
          categoryId: selectedCategoryId as number,
          content: value as string,
        })
        message.success('笔记已修改')
        handleCancel()
      }
    } catch (e: any) {
      console.log(e.message)
      message.error(e.message)
    }
  }

  return (
    <div className="flex justify-center">
      <div className="w-[1000px]">
        <Panel>
          {!isUpgrading ? (
            <div className="text-neutral-1000 text-sm font-semibold">
              写笔记
            </div>
          ) : (
            <div className="text-neutral-1000 text-sm font-semibold">
              修改笔记
            </div>
          )}
          <Divider />
          <Suspense
            fallback={
              <Spin tip="加载编辑器中" className="mt-12">
                {''}
              </Spin>
            }
          >
            <MarkdownEditor
              value={value as string}
              setValue={setValueHandle}
            ></MarkdownEditor>
          </Suspense>
          <Divider />
          <Card title="当前分类">
            <>{selectedCategoryName}</>
          </Card>
          <Card title="公开设置" className="mt-4">
            <div className="flex items-center">
              <Switch
                checked={isPublic === 1}
                onChange={(checked) => setIsPublic(checked ? 1 : 0)}
                className="mr-2"
              />
              <span>
                {isPublic === 1 ? '公开（所有人可见）' : '不公开（仅自己可见）'}
              </span>
            </div>
          </Card>
          <div className="sticky bottom-0 z-20 flex justify-end gap-2">
            {isUpgrading && (
              <>
                <Button icon={<CloseOutlined />} onClick={handleCancel}>
                  取消修改
                </Button>
              </>
            )}
            <Button
              icon={<EyeOutlined />}
              onClick={() => setIsShowPreview(true)}
            >
              预览笔记
            </Button>
            <Button
              icon={<UnorderedListOutlined />}
              onClick={() => setIsShowCategory(true)}
            >
              选择分类
            </Button>
            <Button
              type="primary"
              icon={<Upload />}
              onClick={createNoteClickHandle}
            >
              提交笔记
            </Button>
          </div>
          <Modal
            open={isShowPreview}
            onCancel={() => setIsShowPreview(false)}
            footer={null}
            width={1000}
          >
            <MarkdownRender markdown={value as string} />
          </Modal>
          <Modal
            open={isShowCategory}
            onCancel={() => setIsShowCategory(false)}
            footer={null}
            width={800}
          >
            <CategoryList
              showAdminOp={false}
              showSelectOp={true}
              onCategorySelect={handleCategorySelect}
            />
          </Modal>
        </Panel>
      </div>
    </div>
  )
}
export default NoteWritePage
